package handler

import (
	"api/pkg"
	__ "api/proto"
	"api/request"
	"context"
	"github.com/gin-gonic/gin"
	uuid2 "github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"path/filepath"
	"time"
)

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	if file.Size >= 3*1024*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "文件大小不能超过150m",
			"data": nil,
		})
		return
	}

	uuid := uuid2.NewString()

	ext := filepath.Ext(file.Filename)
	filename := uuid + ext
	dst := "./upload/static/" + filename
	pkg.Upload(dst, filename)
	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, dst)
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "图片上传成功",
		"data": dst,
	})
	return
}

func List(c *gin.Context) {
	var req request.Listreq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "数据验证失败",
			"data": nil,
		})
		return
	}

	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	s := __.NewVideoSrvClient(conn)

	// Contact the server and print out its response.
	_, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := s.ViesList(c, &__.VideoReq{
		Status: req.Status,
		Page:   int64(req.Page),
		Size:   int64(req.Size),
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": r,
	})
}
